package org.snow.maplesnowsniffer;

import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.snow.odinms.ExternalCodeTableGetter;
import org.snow.odinms.HexTool;
import org.snow.odinms.RecvPacketOpcode;
import org.snow.odinms.SendPacketOpcode;

/**
 *
 * @author Raz
 */
public class MapleOpcodeView extends javax.swing.JFrame {

    private static final long serialVersionUID = 4536565449956576701L;
    private boolean showSend = true;
    public static int row;
    public static String name, value;
    private static List<Object[]> sendTableData = null;
    private static List<Object[]> recvTableData = null;
    public boolean isEdited = false;

    /**
     * Creates new form MapleOpcodeView
     */
    public MapleOpcodeView() {
        // <editor-fold defaultstate="collapsed" desc="LookAndFeelInfo">
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MapleOpcodeView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MapleOpcodeView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MapleOpcodeView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MapleOpcodeView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        // </editor-fold>
        initComponents();
        updateTable();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        sendOpcodeRadioButton = new javax.swing.JRadioButton();
        receiveOpcodeRadioButton = new javax.swing.JRadioButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        opcodeTable = new javax.swing.JTable();
        closeButton = new javax.swing.JButton();
        updateHeadersButton = new javax.swing.JButton();
        totalOpcodeLabel = new javax.swing.JLabel();
        saveChangesButton = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Snow's Packet Header Viewer");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        buttonGroup1.add(sendOpcodeRadioButton);
        sendOpcodeRadioButton.setSelected(true);
        sendOpcodeRadioButton.setText("發送的數據包");
        sendOpcodeRadioButton.setToolTipText("Show the send packet opcodes");
        sendOpcodeRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendOpcodeRadioButtonActionPerformed(evt);
            }
        });

        buttonGroup1.add(receiveOpcodeRadioButton);
        receiveOpcodeRadioButton.setText("接收的數據包");
        receiveOpcodeRadioButton.setToolTipText("Show the receive packet opcodes");
        receiveOpcodeRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                receiveOpcodeRadioButtonActionPerformed(evt);
            }
        });

        opcodeTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "名稱", "值"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        opcodeTable.getTableHeader().setReorderingAllowed(false);
        opcodeTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                opcodeTableMouseClicked(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                opcodeTableMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(opcodeTable);
        if (opcodeTable.getColumnModel().getColumnCount() > 0) {
            opcodeTable.getColumnModel().getColumn(1).setMinWidth(120);
            opcodeTable.getColumnModel().getColumn(1).setMaxWidth(120);
        }

        closeButton.setText(Lang.get("opcodeTable.button.close"));
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        updateHeadersButton.setText(Lang.get("opcodeTable.button.update"));
        updateHeadersButton.setToolTipText("Update Headers");
        updateHeadersButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateHeadersButtonActionPerformed(evt);
            }
        });

        totalOpcodeLabel.setText(Lang.get("opcodeTable.total"));

        saveChangesButton.setText(Lang.get("opcodeTable.button.save"));
        saveChangesButton.setToolTipText("Save Header Changes");
        saveChangesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveChangesButtonActionPerformed(evt);
            }
        });

        jButton1.setText(Lang.get("opcodeTable.button.edit"));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(sendOpcodeRadioButton)
                        .addGap(29, 29, 29)
                        .addComponent(totalOpcodeLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(receiveOpcodeRadioButton))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(updateHeadersButton, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(saveChangesButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(closeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sendOpcodeRadioButton)
                    .addComponent(receiveOpcodeRadioButton)
                    .addComponent(totalOpcodeLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 384, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(closeButton)
                    .addComponent(updateHeadersButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(saveChangesButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
	private void sendOpcodeRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendOpcodeRadioButtonActionPerformed
            //SEND
            if (sendOpcodeRadioButton.isSelected()) {
                showSend = true;
                updateTable();
            }
}//GEN-LAST:event_sendOpcodeRadioButtonActionPerformed

	private void receiveOpcodeRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_receiveOpcodeRadioButtonActionPerformed
            //RECEIVE
            if (receiveOpcodeRadioButton.isSelected()) {
                showSend = false;
                updateTable();
            }
}//GEN-LAST:event_receiveOpcodeRadioButtonActionPerformed

	private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
            //CLOSE
            setVisible(false);
            MaplePcaptureGUI.viewPacketHeaderButton.setEnabled(true);
}//GEN-LAST:event_closeButtonActionPerformed

	private void updateHeadersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateHeadersButtonActionPerformed
            //UPDATE
            try {
                sendTableData = null;
                recvTableData = null;
                ExternalCodeTableGetter.populateValues(SendPacketOpcode.getDefaultProperties(), SendPacketOpcode.values());
                ExternalCodeTableGetter.populateValues(RecvPacketOpcode.getDefaultProperties(), RecvPacketOpcode.values());
                updateTable();
                JOptionPane.showMessageDialog(null, Lang.get("opcodeTable.notice.update.ok"), "Update Successful", JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, Lang.get("opcodeTable.notice.update.error"), "Update Error", JOptionPane.ERROR_MESSAGE);
            } catch ( HeadlessException e) {
                JOptionPane.showMessageDialog(null, Lang.get("opcodeTable.notice.update.error"), "Update Error", JOptionPane.ERROR_MESSAGE);
            }
}//GEN-LAST:event_updateHeadersButtonActionPerformed

	private void saveChangesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveChangesButtonActionPerformed
            //SAVE
            JOptionPane.showMessageDialog(null, Lang.get("notDone"), "INFO", JOptionPane.INFORMATION_MESSAGE);
}//GEN-LAST:event_saveChangesButtonActionPerformed

    private void opcodeTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_opcodeTableMouseReleased
        if (evt.isPopupTrigger()) {
            //Get row number
            JTable source = (JTable) evt.getSource();
            row = source.rowAtPoint(evt.getPoint());
            //Show PopupMenu
            JPopupMenu popup = getPopupMenu();
            popup.show(evt.getComponent(), evt.getX(), evt.getY());
        }
    }//GEN-LAST:event_opcodeTableMouseReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // EDIT
        int selectedRow = opcodeTable.getSelectedRow();
        if (selectedRow >= 0) {
            editOpcode(selectedRow);
        } else {
            JOptionPane.showMessageDialog(null, Lang.get("opcodeTable.notice.edit.error"));//, "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void opcodeTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_opcodeTableMouseClicked
        if (evt.getClickCount() == 2 && !evt.isConsumed()) {
            evt.consume();
            int selectedRow = opcodeTable.getSelectedRow();
            editOpcode(selectedRow);
        }
    }//GEN-LAST:event_opcodeTableMouseClicked

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        MaplePcaptureGUI.viewPacketHeaderButton.setEnabled(true);
    }//GEN-LAST:event_formWindowClosed

    public void editOpcode(int row) {
        DefaultTableModel dtm = (DefaultTableModel) opcodeTable.getModel();
        name = dtm.getValueAt(row, 0).toString();
        value = dtm.getValueAt(row, 1).toString();
        new EditOpcode(opcodeTable, name, value);
    }
    
    public JPopupMenu getPopupMenu() {
        JPopupMenu popup = new JPopupMenu();

        Action editAction = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                editOpcode(row);
            }
        };
        JMenuItem copy;
        copy = new JMenuItem(editAction);
        copy.setText("Edit Opcodes");
        popup.add(copy);
        return popup;
    }

    public void updateTable() {
        //if (!isEdited) {
            DefaultTableModel dtm = (DefaultTableModel) opcodeTable.getModel();
            if (dtm.getRowCount() > 0) {
                dtm.getDataVector().removeAllElements();
            }

            if (showSend) {
                if (sendTableData == null || EditOpcode.isEditOpcode) {
                    sendTableData = getRowData();
                }
            } else {
                if (recvTableData == null || EditOpcode.isEditOpcode) {
                    recvTableData = getRowData();
                }
            }
            List<Object[]> toUpdate = showSend ? sendTableData : recvTableData;
            for (Object[] rowData : toUpdate) {
                dtm.addRow(rowData);
            }
            totalOpcodeLabel.setText(Lang.get("opcodeTable.total.update") + toUpdate.size());
        // else {
            //JOptionPane.showMessageDialog(null, "Lưu thay đổi?", "Save Change", JOptionPane.INFORMATION_MESSAGE);
            //isEdited = false;
        //}
    }

    public List<Object[]> getRowData() {
        List<Object[]> ret = new ArrayList<Object[]>();
        if (showSend) {
            for (SendPacketOpcode sOp : SendPacketOpcode.values()) {
                Object[] rowData = new Object[2];
                rowData[0] = sOp.name();
                rowData[1] = HexTool.getOpcodeToString((short) sOp.getValue());
                ret.add(rowData);
            }
            //Update editOpcode
            if (EditOpcode.isEditOpcode) {
                Object[] rowData = new Object[2];
                rowData[0] = name;
                rowData[1] = value;
                ret.set(row, rowData);
                EditOpcode.isEditOpcode = false;
            }
        } else {
            for (RecvPacketOpcode rOp : RecvPacketOpcode.values()) {
                Object[] rowData = new Object[2];
                rowData[0] = rOp.name();
                rowData[1] = HexTool.getOpcodeToString((short) rOp.getValue());
                ret.add(rowData);
            }
            //Update editOpcode
            if (EditOpcode.isEditOpcode) {
                Object[] rowData = new Object[2];
                rowData[0] = name;
                rowData[1] = value;
                ret.set(row, rowData);
                EditOpcode.isEditOpcode = false;
            }
        }
        return ret;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MapleOpcodeView().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton closeButton;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable opcodeTable;
    private javax.swing.JRadioButton receiveOpcodeRadioButton;
    private javax.swing.JButton saveChangesButton;
    private javax.swing.JRadioButton sendOpcodeRadioButton;
    private javax.swing.JLabel totalOpcodeLabel;
    private javax.swing.JButton updateHeadersButton;
    // End of variables declaration//GEN-END:variables
}
